package com.wangtao.groupchat;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenerChannel;
    private static final int PORT = 6667;

    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            listenerChannel = ServerSocketChannel.open();
            listenerChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenerChannel.configureBlocking(false);
            //把listenerChannel注册到Selector关心事件为OP_ACCEPT
            listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听
    public void listener() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey key = keyIterator.next();
                        if (key.isAcceptable()) {
                            //获取socketChannel
                            SocketChannel socketChannel = listenerChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress()+"上线");
                        }
                        if (key.isReadable()) {
                            readData(key);
                        }
                        //删除事件
                        keyIterator.remove();
                    }
                }else{
                    System.out.println("等待...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    //读取客户端消息
    public void readData(SelectionKey selectionKey) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(byteBuffer);
            if (count > 0) {
                String msg = new String(byteBuffer.array());
                //输出消息
                System.out.println("form 客户端" + msg);
                //向其他客户端转发消息
                sendInfoOtherClients(msg, socketChannel);
            }
        } catch (Exception e) {
            try {
                System.out.println( socketChannel.getRemoteAddress()+"离线");
                //取消注册
                selectionKey.cancel();
                //关闭通道
                socketChannel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    //转发消息给其他客户端
    private void sendInfoOtherClients(String msg,SocketChannel socketChannel) {
        System.out.println("服务器转发消息中...");
        //遍历所有注册到selector上的SocketChannel，并排除自己
        selector.keys().forEach(item->{
            //通过key取出对应的SocketChannel
            Channel channel = item.channel();
            //排除自己
            if (channel instanceof SocketChannel && channel != socketChannel) {
                SocketChannel dest = (SocketChannel) channel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                try {
                    dest.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listener();
    }
}
